import { useState, useEffect, useCallback, useRef } from 'react'
import Taro from '@tarojs/taro'

// IndexedDB 配置
const DB_CONFIG = {
  name: 'CosmeticSurgeryDB',
  version: 1,
  stores: {
    cache: 'cache',
    searchHistory: 'searchHistory',
    userPreferences: 'userPreferences'
  }
}

// IndexedDB 管理器
class IndexedDBManager {
  constructor() {
    this.db = null
    this.isInitialized = false
  }

  // 初始化数据库
  async init() {
    if (this.isInitialized) return this.db

    return new Promise((resolve, reject) => {
      // 在小程序环境中，使用 Taro 的存储API作为备选方案
      if (typeof indexedDB === 'undefined') {
        console.warn('IndexedDB not available, falling back to Taro storage')
        this.isInitialized = true
        resolve(null)
        return
      }

      const request = indexedDB.open(DB_CONFIG.name, DB_CONFIG.version)

      request.onerror = () => {
        console.error('Failed to open IndexedDB')
        reject(new Error('Failed to open IndexedDB'))
      }

      request.onsuccess = () => {
        this.db = request.result
        this.isInitialized = true
        resolve(this.db)
      }

      request.onupgradeneeded = (event) => {
        const db = event.target.result

        // 创建缓存存储
        if (!db.objectStoreNames.contains(DB_CONFIG.stores.cache)) {
          const cacheStore = db.createObjectStore(DB_CONFIG.stores.cache, { keyPath: 'key' })
          cacheStore.createIndex('timestamp', 'timestamp', { unique: false })
          cacheStore.createIndex('ttl', 'ttl', { unique: false })
        }

        // 创建搜索历史存储
        if (!db.objectStoreNames.contains(DB_CONFIG.stores.searchHistory)) {
          const historyStore = db.createObjectStore(DB_CONFIG.stores.searchHistory, { keyPath: 'id', autoIncrement: true })
          historyStore.createIndex('keyword', 'keyword', { unique: false })
          historyStore.createIndex('timestamp', 'timestamp', { unique: false })
        }

        // 创建用户偏好存储
        if (!db.objectStoreNames.contains(DB_CONFIG.stores.userPreferences)) {
          const prefsStore = db.createObjectStore(DB_CONFIG.stores.userPreferences, { keyPath: 'key' })
        }
      }
    })
  }

  // 存储数据
  async set(storeName, key, value, ttl = null) {
    if (!this.isInitialized) await this.init()

    if (!this.db) {
      // 使用 Taro 存储作为备选
      return this.setTaroStorage(key, value, ttl)
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)

      const data = {
        key,
        value,
        timestamp: Date.now(),
        ttl: ttl ? Date.now() + ttl : null
      }

      const request = store.put(data)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(request.error)
    })
  }

  // 获取数据
  async get(storeName, key) {
    if (!this.isInitialized) await this.init()

    if (!this.db) {
      // 使用 Taro 存储作为备选
      return this.getTaroStorage(key)
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([storeName], 'readonly')
      const store = transaction.objectStore(storeName)
      const request = store.get(key)

      request.onsuccess = () => {
        const data = request.result
        if (!data) {
          resolve(null)
          return
        }

        // 检查是否过期
        if (data.ttl && Date.now() > data.ttl) {
          this.delete(storeName, key)
          resolve(null)
          return
        }

        resolve(data.value)
      }

      request.onerror = () => reject(request.error)
    })
  }

  // 删除数据
  async delete(storeName, key) {
    if (!this.isInitialized) await this.init()

    if (!this.db) {
      // 使用 Taro 存储作为备选
      return this.deleteTaroStorage(key)
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)
      const request = store.delete(key)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(request.error)
    })
  }

  // 清理过期数据
  async cleanup(storeName) {
    if (!this.isInitialized) await this.init()

    if (!this.db) return

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)
      const index = store.index('ttl')
      const request = index.openCursor()

      request.onsuccess = () => {
        const cursor = request.result
        if (cursor) {
          const data = cursor.value
          if (data.ttl && Date.now() > data.ttl) {
            cursor.delete()
          }
          cursor.continue()
        } else {
          resolve()
        }
      }

      request.onerror = () => reject(request.error)
    })
  }

  // Taro 存储备选方案
  async setTaroStorage(key, value, ttl = null) {
    try {
      const data = {
        value,
        timestamp: Date.now(),
        ttl: ttl ? Date.now() + ttl : null
      }
      await Taro.setStorageSync(`cache_${key}`, JSON.stringify(data))
    } catch (error) {
      console.error('Taro storage set error:', error)
    }
  }

  async getTaroStorage(key) {
    try {
      const dataStr = await Taro.getStorageSync(`cache_${key}`)
      if (!dataStr) return null

      const data = JSON.parse(dataStr)
      
      // 检查是否过期
      if (data.ttl && Date.now() > data.ttl) {
        await this.deleteTaroStorage(key)
        return null
      }

      return data.value
    } catch (error) {
      console.error('Taro storage get error:', error)
      return null
    }
  }

  async deleteTaroStorage(key) {
    try {
      await Taro.removeStorageSync(`cache_${key}`)
    } catch (error) {
      console.error('Taro storage delete error:', error)
    }
  }
}

// 全局 IndexedDB 管理器
const dbManager = new IndexedDBManager()

// 持久化缓存 Hook
export const usePersistentCache = () => {
  const [isReady, setIsReady] = useState(false)
  const cacheRef = useRef(new Map())

  // 初始化
  useEffect(() => {
    const initDB = async () => {
      try {
        await dbManager.init()
        setIsReady(true)
      } catch (error) {
        console.error('Failed to initialize persistent cache:', error)
        setIsReady(true) // 即使失败也设置为就绪，使用内存缓存
      }
    }

    initDB()
  }, [])

  // 设置缓存
  const setCache = useCallback(async (key, value, ttl = null) => {
    // 同时更新内存缓存和持久化缓存
    cacheRef.current.set(key, {
      value,
      timestamp: Date.now(),
      ttl: ttl ? Date.now() + ttl : null
    })

    try {
      await dbManager.set(DB_CONFIG.stores.cache, key, value, ttl)
    } catch (error) {
      console.error('Failed to set persistent cache:', error)
    }
  }, [])

  // 获取缓存
  const getCache = useCallback(async (key) => {
    // 先检查内存缓存
    const memoryCache = cacheRef.current.get(key)
    if (memoryCache) {
      // 检查是否过期
      if (memoryCache.ttl && Date.now() > memoryCache.ttl) {
        cacheRef.current.delete(key)
      } else {
        return memoryCache.value
      }
    }

    // 从持久化缓存获取
    try {
      const value = await dbManager.get(DB_CONFIG.stores.cache, key)
      if (value !== null) {
        // 更新内存缓存
        cacheRef.current.set(key, {
          value,
          timestamp: Date.now(),
          ttl: null // 持久化缓存已经处理了TTL
        })
      }
      return value
    } catch (error) {
      console.error('Failed to get persistent cache:', error)
      return null
    }
  }, [])

  // 删除缓存
  const deleteCache = useCallback(async (key) => {
    cacheRef.current.delete(key)
    try {
      await dbManager.delete(DB_CONFIG.stores.cache, key)
    } catch (error) {
      console.error('Failed to delete persistent cache:', error)
    }
  }, [])

  // 清理过期缓存
  const cleanupCache = useCallback(async () => {
    // 清理内存缓存
    const now = Date.now()
    for (const [key, data] of cacheRef.current.entries()) {
      if (data.ttl && now > data.ttl) {
        cacheRef.current.delete(key)
      }
    }

    // 清理持久化缓存
    try {
      await dbManager.cleanup(DB_CONFIG.stores.cache)
    } catch (error) {
      console.error('Failed to cleanup persistent cache:', error)
    }
  }, [])

  // 获取缓存统计
  const getCacheStats = useCallback(() => {
    return {
      memorySize: cacheRef.current.size,
      isReady
    }
  }, [isReady])

  return {
    isReady,
    setCache,
    getCache,
    deleteCache,
    cleanupCache,
    getCacheStats
  }
}

// 搜索历史持久化 Hook
export const usePersistentSearchHistory = () => {
  const [history, setHistory] = useState([])
  const [isReady, setIsReady] = useState(false)

  // 初始化
  useEffect(() => {
    const initHistory = async () => {
      try {
        await dbManager.init()
        
        // 从持久化存储加载历史
        const storedHistory = await dbManager.get(DB_CONFIG.stores.searchHistory, 'searchHistory')
        if (storedHistory) {
          setHistory(storedHistory)
        }
        
        setIsReady(true)
      } catch (error) {
        console.error('Failed to initialize search history:', error)
        setIsReady(true)
      }
    }

    initHistory()
  }, [])

  // 添加搜索历史
  const addHistory = useCallback(async (keyword) => {
    if (!keyword || !keyword.trim()) return

    const trimmedKeyword = keyword.trim()
    const newHistory = [
      trimmedKeyword,
      ...history.filter(h => h !== trimmedKeyword)
    ].slice(0, 10) // 最多保留10条

    setHistory(newHistory)

    try {
      await dbManager.set(DB_CONFIG.stores.searchHistory, 'searchHistory', newHistory)
    } catch (error) {
      console.error('Failed to save search history:', error)
    }
  }, [history])

  // 清除历史
  const clearHistory = useCallback(async () => {
    setHistory([])
    try {
      await dbManager.delete(DB_CONFIG.stores.searchHistory, 'searchHistory')
    } catch (error) {
      console.error('Failed to clear search history:', error)
    }
  }, [])

  return {
    history,
    isReady,
    addHistory,
    clearHistory
  }
}

// 用户偏好持久化 Hook
export const usePersistentUserPreferences = () => {
  const [preferences, setPreferences] = useState({})
  const [isReady, setIsReady] = useState(false)

  // 初始化
  useEffect(() => {
    const initPreferences = async () => {
      try {
        await dbManager.init()
        
        // 从持久化存储加载偏好
        const storedPrefs = await dbManager.get(DB_CONFIG.stores.userPreferences, 'userPreferences')
        if (storedPrefs) {
          setPreferences(storedPrefs)
        }
        
        setIsReady(true)
      } catch (error) {
        console.error('Failed to initialize user preferences:', error)
        setIsReady(true)
      }
    }

    initPreferences()
  }, [])

  // 设置偏好
  const setPreference = useCallback(async (key, value) => {
    const newPreferences = { ...preferences, [key]: value }
    setPreferences(newPreferences)

    try {
      await dbManager.set(DB_CONFIG.stores.userPreferences, 'userPreferences', newPreferences)
    } catch (error) {
      console.error('Failed to save user preferences:', error)
    }
  }, [preferences])

  // 获取偏好
  const getPreference = useCallback((key, defaultValue = null) => {
    return preferences[key] !== undefined ? preferences[key] : defaultValue
  }, [preferences])

  return {
    preferences,
    isReady,
    setPreference,
    getPreference
  }
}

export default usePersistentCache
